<?php

namespace builder\test\controllers;

use builder\base\BaseController;
use builder\form\FormBuilder;
use builder\helper\H5;
use builder\tree\TreeBuilder;
use builder\widget\ajax\BlockAjax;
use builder\widget\WidgetFacade;

/**
 * 表单
 */
class FormController extends BaseController
{
    public $publicActions = [
        'index',
        'tree',
        'submit',
        'dynamic',
        'dynamic2',
    ];
    public $actionVerbs = [
        'index' => ['GET', 'POST'],
        'tree' => ['GET', 'POST'],
        'submit' => ['GET', 'POST'],
        'dynamic' => ['GET', 'POST'],
        'dynamic2' => ['GET', 'POST'],
    ];

    public function actionTree()
    {
        $treeBuilder = TreeBuilder::instance(['id' => 'Form_Tree']);

        if ($this->isAjax) {
            return $treeBuilder->setData(function () {
                $result = [];
                $result[] = [
                    'title' => '醉里',
                    'id' => 1,
                    'children' => [
                        [
                            'title' => '挑灯',
                            'id' => 11,
                            'children' => [
                                [
                                    'title' => '看剑',
                                    'id' => 12,
                                ],
                                [
                                    'title' => '梦回吹角连营',
                                    'id' => 121,
                                ]
                            ],
                        ]
                    ],
                ];
                $result[] = [
                    'title' => '窗前',
                    'id' => 2,
                    'children' => [
                        [
                            'title' => '明月',
                            'id' => 21,
                            'children' => [
                                [
                                    'title' => '光',
                                    'id' => 22,
                                ],
                                [
                                    'title' => '疑是地上霜',
                                    'id' => 221,
                                ]
                            ],
                        ]
                    ],
                ];

                return $result;
            })->render();
        } else {
            return $treeBuilder->setTitle('树组件构建')
                ->setPartial()
                ->registerPointcut(H5::alert('头部切点'))
                ->setDefaultText('')
                ->setOnlyIconControl(false)
                ->setSwitchCheckedBtn()
                ->setSwitchSpreadBtn()
                ->setShowLine(false)
                ->setRootLayout([
                    'class' => 'col-md-3'
                ])
                ->setTreeLayout([
                    'style' => ['height' => '500px', 'overflow' => 'auto'],
                ])->render();
        }
    }

    public function actionSubmit()
    {
        return $this->asFail();
    }

    //表单示例
    public function actionIndex()
    {
        $formBuilder = FormBuilder::instance(['id' => 'Form_Index']);
        $formBuilder->setTitle('表单示例')
            ->setPartial(!!@$this->get['_partial'])
            ->setGroup('默认表单分组1', 'default1')
            ->setGroupCol(4)
            ->setGroupComment('这是分组1注释!')
            ->setFormControl([
                'Field1' => $this->formControl
                    ->text()
                    ->label('文本1：')
                    ->maxLength(255)
                    ->defaultValue('这是含有前缀和后缀的一段文本1')
                    ->prefix('http(s)://')
                    ->suffix(WidgetFacade::echo2Return(function () {
                        BlockAjax::begin([
                            'url' => 'ymtest/form/submit',
                            'ajaxFailureCallback' => 'console.log(scope.$parent.default1.Field1=2)',
                            'scope' => [
                                'p1' => 'default1[\'Field1\']',
                                'p2' => 'default1[\'Field2\']',
                            ],
                        ]);
                        echo H5::buttonSuffix('打开');
                        BlockAjax::end();
                    }))
                    ->datalist([
                        'option1',
                        'option2',
                        'option3',
                        'option4',
                        'option5',
                    ])
                    ->required(),
                'Field6' => $this->formControl->password()->label('文本2：')->required()->checkRule('/^\d+$/g'),
                'Field2' => $this->formControl
                    ->number()
                    ->label('数字：')
                    ->prefix('http(s)://')
                    ->suffix(WidgetFacade::echo2Return(function () {
                        BlockAjax::begin([
                            'url' => 'ymtest/form/submit',
                            'ajaxFailureCallback' => 'console.log(scope.$parent.default1.Field2=15090321514)',
                            'scope' => [
                                'p1' => 'default1[\'Field1\']',
                                'p2' => 'default1[\'Field2\']',
                            ],
                        ]);
                        echo H5::buttonSuffix('打开');
                        BlockAjax::end();
                    }))
                    ->defaultValue('这是一段数字')
                    ->required(),
                'Field3' => $this->formControl->file()->label('文件：')->max(2)->scenarioImage()->required(),
                'Field4' => $this->formControl->time()->label('时间：')->required(),
                'Field5' => $this->formControl->tag()->label('动态标签：')->remote()->modalRoute('ymtest/form/tree')->modalTitle('请选择')->modalCallId('Form_Tree')->modalCloseOnSelected(),
                //'Field0' => $this->formControl->datetime()->range(1)->label('月：'),
                //'Field7' => $this->formControl
                //    ->number()
                //    ->label('数字2：')
                //    ->defaultValue('这是一段数字')
                //    ->required(),
                //'Field8' => $this->formControl
                //    ->select()
                //    ->label('下拉框')
                //    ->options(['f1', 'f2']),
            ])
            ->setGroup('默认表单分组2', 'default2')
            ->setGroupCol(4)
            ->setGroupComment('这是分组2注释!')
            ->setFormControl([
                'Field6' => $this->formControl->textarea()->label('文本域：')->maxLength(255)->required(),
                'Field7' => $this->formControl->checkbox()->label('多选：')->tag()->options(['Option1' => 'Option1', 'Option2' => 'Option2', 'Option3' => 'Option3'])->required(),
                'Field8' => $this->formControl->radio()->label('Radio：')->options(['包包', '鞋子'])->required(),
                'Field9' => $this->formControl->date()->label('日期：')->required(),
                'Field10' => $this->formControl->year()->label('年：'),
                'Field11' => $this->formControl->month()->label('月：'),
            ])
            ->setGroup('默认表单分组3', 'default3')
            ->setGroupCol(4)
            ->setGroupComment('这是分组3注释!')
            ->setFormControl([
                'Field12' => $this->formControl->trigger()->uiClass(['w-100'])->when('default2', 'Field8', '==', '1')->triggerItems([
                    'Field12_1' => $this->formControl->xselect()->label('Xselect：')->data([
                        ['name' => '选项1', 'value' => 1],
                        ['name' => '选项2', 'value' => 2],
                        ['name' => '选项3', 'value' => 3],
                    ])->radio(),
                ])->display(),
                'Field13' => $this->formControl->richeTextTinyMCE()->label('富文本：')->config(['height' => 280]),
                'Field14' => $this->formControl->star()->label('星评：'),
                'Field15' => $this->formControl->section()->label('区间：'),
            ])
            ->setResetBtn()
            ->setSubmitBtn()
            ->setSubmitConfirm()
            ->setAutoClose();

        return $formBuilder->render();
    }

    public function actionDynamic()
    {
        if ($this->isPost) {
            return $this->asFail('保存失败！');
        } else {
            $jsCallback = <<<JS
return function(obj){
  console.log(obj.elem); // 点击的元素
  console.log(obj.data); // 得到点击项的数据
  console.log(obj.index); // 如果数据来自左边，index 为 0，否则为 1
  return false // 返回 false 会阻止穿梭
}
JS;
            $cancelHandler = <<<JS
return function(value){
    console.log('cancelHandler', value);
};
JS;
            $changeHandler = <<<JS
return function(value){
    console.log('changeHandler', value);
};
JS;
            $closeHandler = <<<JS
return function(value){
    console.log('closeHandler', value);
};
JS;
            return FormBuilder::instance(['id' => 'Form_Dynamic'])
                ->setPartial(!empty($this->get['_partial']))
                ->setRootLayout([
                    'class' => ['col-8', 'offset-2'],
                ])
                ->setFormControl([
                    'selecLayui' => $this->formControl->selectLayui()->label('下拉选择Layui')->layout(12)->options([
                        ['value' => 'tom1', 'label' => '汤姆猫1', 'disabled' => false],
                        ['value' => 'tom2', 'label' => '汤姆猫2', 'disabled' => false],
                        ['value' => 'tom3', 'label' => '汤姆猫3', 'disabled' => true],
                    ])->search(true)->placeholder('请选择这些')->required()->comment('这是备注')->attribute(['data-test' => 1])->help('这是帮助')
                ->style(['background-color' => 'white'])->defaultValue('tom2')->creatable(true)->search_caseSensitive(true)->search_fuzzy(true),
                    'colorPicker' => $this->formControl->colorpicker()->label('颜色拾取')->defaultValue('rgba(100,125,50,1)')->style(['background-color' => '#fff'])
                        ->help('这是一个帮助。')->attribute(['title' => '这是属性'])->comment('这是一个注释。')->required()
                        ->layout(12)->setting_alpha(true)->setting_colors(['rgba(100,125,50,.5)', 'rgba(0,0,0,1)', 'rgba(50,100,255,1)'])->setting_format('rgb')
                        ->setting_predefine(true)->setting_size('lg')->event_cancel($cancelHandler)->event_change($changeHandler)->event_close($closeHandler),
                    'trans' => $this->formControl->transfer()->label('穿梭')->layout(12)->required()->comment('这是注释。')->attribute(['title' => '这是属性'])
                        ->help('这是帮助。')->style(['background-color' => '#fff'])->defaultValue(['yang', 'li', 'wang'])->setting_data([
                            ['title' => '杨', 'value' => 'yang', 'checked' => false, 'disabled' => false],
                            ['title' => '李', 'value' => 'li', 'checked' => false, 'disabled' => false],
                            ['title' => '王', 'value' => 'wang', 'checked' => false, 'disabled' => false],
                            ['title' => '赵', 'value' => 'zhao', 'checked' => false, 'disabled' => false],
                            ['title' => '孙', 'value' => 'sun', 'checked' => false, 'disabled' => false],
                            ['title' => '苏', 'value' => 'su', 'checked' => false, 'disabled' => false],
                            ['title' => '公孙', 'value' => 'gongsun', 'checked' => false, 'disabled' => false],
                        ])->setting_height(300)->setting_showSearch(true)->setting_title(['左', '右'])->setting_width(200)->setting_text([
                            'none' => '嘿，无数据', // 没有数据时的文案
                            'searchNone' => '嘿，无匹配数据', // 搜索无匹配数据时的文案
                        ])->event_dbClick($jsCallback),
                    'text1' => $this->formControl->text()->label('文本')->required()->checkRule('/^\w+$/'),
                    'sw1' => $this->formControl->sw()->label('开关'),
                    'trigger' => $this->formControl->trigger()->when('default', 'sw1', '===', 1)->triggerItems([
                        'dnm' => $this->formControl->dynamicControl()
                            ->label('内容')
                            ->data([
                                ['number1' => '1000', 'text2' => '张三'],
                                ['number1' => '2000', 'text2' => '李四'],
                            ])
                            ->items([
                                'number1' => $this->dynamicControl->number()->label('数字')->required()->checkRule('/^\d+\.?\d{0,2}$/'),
                                'text2' => $this->dynamicControl->text()->label('文本')->required()->checkRule('/^\w+$/'),
                            ]),
                    ])->display(),
                ])
                ->setResetBtn('重 置')
                ->setSubmitBtn()
                ->render();
        }
    }

    // 动态表单
    public function actionDynamic2()
    {
        if ($this->isAjax) {
            return $this->asOk();
        } else {
            $data = [];
            for ($i = 0; $i < 10; $i++) {
                $data[] = ['dc1' => '', 'dc2' => '', 'dc3' => ''];
            }
            return FormBuilder::instance(['id' => 'BID_Form_Dynamic2'])
                ->setPartial(!!@$this->get['_partial'])
                ->setTitle('动态表单')
                ->setGroupCol(6)
                ->setFormControl([
                    'field1' => $this->formControl->text()->label('方案标题')->defaultValue('立交桥运动场规划方案')->maxLength(50)->required(),
                    'field2' => $this->formControl->dynamicControl()->label('场景规划')->skinAttribute(['lay-skin' => 'nob', 'lay-even' => ''])->items([
                        'dc1' => $this->dynamicControl->text()->label('名称')->required()->minWidth(120),
                        'dc2' => $this->dynamicControl->number()->label('数量')->required()->minWidth(120),
                        'dc3' => $this->dynamicControl->date()->label('时间')->range()->required()->minWidth(200),
                    ])->skinAttribute(['lay-skin' => 'grid'])->allowDragSorting()->hideAddBtn()->comment('注：规划是指一个周期内环比增长导向计划')->data($data),
                ])
                ->setCloseBtn()
                ->setResetBtn()
                ->setSubmitBtn()
                ->setAutoClose()
                ->setFooterFixed(false)
                ->setFooterLayout(['class' => 'text-left'])
                ->render();
        }
    }
}